package com.topsoft.micro.web;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.topsoft.micro.data.CacheData;
import com.zzy.core.utils.FastJsonUtil;

@RestController
public class UserController {

	@RequestMapping("/user/index")
	public Authentication user(Authentication authentication) {
		return authentication;
	}

	@RequestMapping("/user/me")
	public Principal user(HttpServletRequest request, HttpServletResponse response, Principal principal,
			Authentication authentication, HttpSession httpSession) {

		String username = principal.getName();

		String authenticationStr = FastJsonUtil.fastJsonSerialize(authentication);

		System.out.println("````````/user/me``````````" + authenticationStr);

		JSONObject jsonObj = JSONObject.parseObject(authenticationStr);

		JSONObject details = jsonObj.getJSONObject("details");
		JSONObject oAuth2Request = jsonObj.getJSONObject("oAuth2Request");

		String tokenValue = details.getString("tokenValue");
		String clientId = oAuth2Request.getString("clientId");

		if (null == CacheData.tokenMap.get(username)) {
			CacheData.tokenMap.put(username, Sets.newHashSet());
		}
		if (null == CacheData.clientIdMap.get(username)) {
			CacheData.clientIdMap.put(username, Sets.newHashSet());
		}
		CacheData.tokenMap.get(username).add(tokenValue);
		CacheData.clientIdMap.get(username).add(clientId);

		return principal;
	}

}
